<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Value_mdl extends CI_Model {

    const TABLE = 'sort_value';

    /**
     * 系统默认添加商品属性列表
     * @param  array    $data   当前商品表的所有分类属性
     * @param  int      $gid    当前商品ID
     * @return array    $gvalue 商品属性值
     */
    public function create($data,$gid){
        $gvalue = [];
        foreach($data as $k => $v){

            foreach($v['tree'] as $key => $value){
                $res = $this->is_set($value['id'],$gid);
                if($res === false){
                    //添加属性
                    $data = [
                        'att_id' => $value['id'],
                        'goods_id' => $gid,
                        'value' => $value['avalue']
                    ];
                    $this->db->insert(self::TABLE,$data);
                    $data['id'] = $this->db->insert_id();
                    $res = $data;
                }
                $gvalue[$value['id']] = $res;
            }

        }

        //清理作废的字段
        $vid = '';
        foreach ($gvalue as $key => $value) {
            $vid .= $value['id'].',';
        }

        if(!empty($vid)){
            $vid = substr($vid,0,-1);
            $this->db->where("`goods_id` = $gid AND id NOT IN($vid)");
            $this->db->delete(self::TABLE);
        }

        return $gvalue;
    }

    /**
     * 判断当前属性是否存在
     * @return boolean 
     */
    public function is_set($aid,$gid){
        $this->db->where('att_id',$aid);
        $this->db->where('goods_id',$gid);
        $this->db->select('id,att_id,value');
        $res = $this->db->get(self::TABLE)->row_array();
        if(empty($res)){
            return false;
        }
        return $res;
    }

    public function update($data){
        $this->db->set($data);
        return $this->db->update(self::TABLE);
    }

    public function delete(){
        return $this->db->delete(slef::TABLE);
    }

}

/* End of file value_mdl.php */
/* Location: ./application/models/value_mdl.php */